﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HHPS.CreditEducation.DataProvider;
using HHPS.CreditEducation.Frameworks.Commons;
using HHPS.CreditEducation.Frameworks.Constants;

namespace HHPS.CreditEducation.Presentation.Materials
{
    public partial class SubjectControl : UserControl
    {
        private readonly Business.Business _business;

        public SubjectControl()
        {
            InitializeComponent();

            _business = MainView.Instance.CreditEducationBusiness;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubjectControlLoad(object sender, EventArgs e)
        {
            Dock = DockStyle.Top;

            LoadKindOfSubject();
        }

        #region -- Kind of subject --

        /// <summary>
        /// 
        /// </summary>
        private void LoadKindOfSubject()
        {
            dgvKindOfSubjectList.DataSource = _business.GetListKindOfSubject();

            DataGridViewHelper.ChangeDgvStyleDataGridView(dgvKindOfSubjectList);

            DataGridViewHelper.ApplyUncheckedAll(dgvKindOfSubjectList);

            KindOfSubjectCurrentRowChanged();

            LoadSubject();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="kindofsubject"></param>
        private void ReloadKindOfSubject(KindOfSubject kindofsubject)
        {
            LoadKindOfSubject();
            DataGridViewHelper.SetDgvCurrentCell(dgvKindOfSubjectList, kindofsubject.Name);
            KindOfSubjectCurrentRowChanged();
            if (dgvKindOfSubjectList != null && dgvKindOfSubjectList.RowCount > 0)
            {
                txtKindOfSubject.SelectAll();
            }
            else txtKindOfSubject.Text = string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        private void KindOfSubjectCurrentRowChanged()
        {
            if (dgvKindOfSubjectList.CurrentRow != null)
            {
                txtKindOfSubject.Text = dgvKindOfSubjectList.CurrentRow.Cells[PropertiesConstants.Name].Value.ToString();

                LoadSubject();
            }
            else
            {
                lblKindOfSubject.Text = string.Format(ConstantMessages.LabelKindOfSubject, "...");

                txtKindOfSubject.Text = string.Empty;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvKindOfSubjectListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvKindOfSubjectList == null) return;

            if (e.ColumnIndex != dgvKindOfSubjectList.Columns[PropertiesConstants.IsChecked].Index) return;

            dgvKindOfSubjectList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvKindOfSubjectList[e.ColumnIndex, e.RowIndex].Value;

            switch ((bool)dgvKindOfSubjectList[e.ColumnIndex, e.RowIndex].Value)
            {
                case false:
                    {
                        ckbAllKindOfSubject.Checked = false;

                        ckbAllKindOfSubject.Text = string.Format("Lựa chọn tất cả");
                    }
                    break;

                default:
                    if (DataGridViewHelper.AllRowsIsCheck(dgvKindOfSubjectList))
                    {
                        ckbAllKindOfSubject.Checked = true;

                        ckbAllKindOfSubject.Text = string.Format("Hủy chọn tất cả");
                    }
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvKindOfSubjectListCurrentCellChanged(object sender, EventArgs e)
        {
            KindOfSubjectCurrentRowChanged();
        }

        private void CkbAllKindOfSubjectCheckedChanged(object sender, EventArgs e)
        {
            if (ckbAllKindOfSubject.Checked)
            {
                DataGridViewHelper.ApplyCheckedAll(dgvKindOfSubjectList);

                ckbAllKindOfSubject.Text = string.Format("Hủy chọn tất cả");
            }
            else
            {
                DataGridViewHelper.ApplyUncheckedAll(dgvKindOfSubjectList);
                ckbAllKindOfSubject.Text = string.Format("Lựa chọn tất cả");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddKindOfSubjectClick(object sender, EventArgs e)
        {
            try
            {
                var kindOfSubject = new KindOfSubject { Name = txtKindOfSubject.Text.Trim() };
                string message;

                if (_business.AddNewKinhOfSubectValidator(kindOfSubject, out message))
                {
                    _business.AddNewKindOfSubject(kindOfSubject);

                    ReloadKindOfSubject(kindOfSubject);
                }
                else
                    MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditKindOfSubjectClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvKindOfSubjectList.CurrentRow != null)
                {
                    var kindOfSubject = new KindOfSubject
                    {
                        Id = Convert.ToInt32(dgvKindOfSubjectList.CurrentRow.Cells[(string)typeof(KindOfSubject).Properties().Id].Value),
                        Name = txtKindOfSubject.Text.Trim()
                    };
                    string message;

                    if (_business.EditKindOfSubjectValidator(kindOfSubject, out message))
                    {
                        if (!_business.EditKindOfSubject(kindOfSubject))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.PROGRAM_NAME);
                            return;
                        }
                        ReloadKindOfSubject(kindOfSubject);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteKindOfSubjectClick(object sender, EventArgs e)
        {
            try
            {
                var kindOfSubjects = new List<KindOfSubject>();
                string message;

                for (var i = 0; i < dgvKindOfSubjectList.RowCount; i++)
                {
                    if (!(bool)dgvKindOfSubjectList[(string)typeof(KindOfSubject).Properties().IsChecked, i].Value) continue;

                    kindOfSubjects.Add(new KindOfSubject
                    {
                        Id = (int)dgvKindOfSubjectList[(string)typeof(KindOfSubject).Properties().Id, i].Value,
                        Name = dgvKindOfSubjectList[(string)typeof(KindOfSubject).Properties().Name, i].Value.ToString()
                    });
                }

                if (kindOfSubjects.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                    return;
                }

                if (_business.DeleteKindOfsubjectsValidator(kindOfSubjects, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các loại môn học đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteKindOfSubjects(kindOfSubjects);
                        ReloadKindOfSubject(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- Subject --

        /// <summary>
        /// This fuction loads Subject to datagridview
        /// </summary>
        private void LoadSubject()
        {
            if (dgvKindOfSubjectList.CurrentRow == null) return;

            string keyword = txtSearchSubject.Text.Trim().ToLower();

            var idKindOfSubject = Convert.ToInt32(dgvKindOfSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value);
            var nameKindOfSubject = (dgvKindOfSubjectList.CurrentRow.Cells[PropertiesConstants.Name].Value);

            dgvSubjectList.DataSource = _business.GetListSubjectByKindOfSubject(idKindOfSubject, keyword);

            lblKindOfSubject.Text = string.Format(ConstantMessages.LabelKindOfSubject, nameKindOfSubject);

            DataGridViewHelper.ShowHideColumns(dgvSubjectList,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name, "NumberOfCredit" });
            DataGridViewHelper.ShowIsCheck(dgvSubjectList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubjectList, false);

            SubjectCurrentRowChanged();
        }

        private void txtSearchSubject_TextChanged(object sender, EventArgs e)
        {
            LoadSubject();
        }

        private void ReloadSubject(Subject subject)
        {
            LoadSubject();
            DataGridViewHelper.SetDgvCurrentCell(dgvSubjectList, subject.Name);
            SubjectCurrentRowChanged();
            if (dgvSubjectList != null && dgvSubjectList.RowCount > 0)
            {
                txtSubject.SelectAll();
            }
            else txtSubject.Text = string.Empty;
        }

        private void SubjectCurrentRowChanged()
        {
            if (dgvSubjectList.CurrentRow != null)
            {
                txtSubject.Text = dgvSubjectList.CurrentRow.Cells[PropertiesConstants.Name].Value.ToString();
                nudNumberOfCredit.Value =
                    Convert.ToInt16(dgvSubjectList.CurrentRow.Cells["NumberOfCredit"].Value);
                LoadSubjectRequired();
            }
            else
            {
                txtSubject.Text = string.Empty;
                nudNumberOfCredit.Value = 0;
                ckbAllSubject.Checked = false;
                ckbAllSubject.Text = string.Format("Lựa chọn tất cả");

                lblSubject.Text = string.Format(ConstantMessages.LabelSubject, ConstantMessages.NoSelected);
            }
        }

        private void DgvSubjectListCurrentCellChanged(object sender, EventArgs e)
        {
            SubjectCurrentRowChanged();
        }

        private void CkbAllSubjectCheckedChanged(object sender, EventArgs e)
        {
            if (ckbAllSubject.Checked)
            {
                DataGridViewHelper.ApplyCheckedAll(dgvSubjectList);

                ckbAllSubject.Text = string.Format("Hủy chọn tất cả");
            }
            else
            {
                DataGridViewHelper.ApplyUncheckedAll(dgvSubjectList);

                ckbAllSubject.Text = string.Format("Lựa chọn tất cả");
            }
        }

        private void DgvSubjectListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSubjectList == null) return;
            if (e.ColumnIndex != dgvSubjectList.Columns[PropertiesConstants.IsChecked].Index) return;
            dgvSubjectList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvSubjectList[e.ColumnIndex, e.RowIndex].Value;

            switch ((bool)dgvSubjectList[e.ColumnIndex, e.RowIndex].Value)
            {
                case false:
                    {
                        ckbAllSubject.Checked = false;

                        ckbAllSubject.Text = string.Format("Lựa chọn tất cả");
                    }
                    break;
                default:
                    if (DataGridViewHelper.AllRowsIsCheck(dgvSubjectList))
                    {
                        ckbAllSubject.Checked = true;

                        ckbAllSubject.Text = string.Format("Hủy chọn tất cả");
                    }
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddSubjectClick(object sender, EventArgs e)
        {
            try
            {
                var subject = new Subject
                {
                    Name = txtSubject.Text.Trim(),
                    NumberOfCredit = (int)nudNumberOfCredit.Value,
                    IdKindOfSubject = dgvKindOfSubjectList.CurrentRow != null ?
                    Convert.ToInt32(dgvKindOfSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value) : 0
                };

                string message;

                if (_business.AddNewSubjectValidator(subject, out message))
                {
                    _business.AddNewSubject(subject);

                    ReloadSubject(subject);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnEditSubjectClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvSubjectList.CurrentRow != null)
                {
                    var subject = new Subject
                    {
                        Name = txtSubject.Text.Trim(),
                        NumberOfCredit = (int)nudNumberOfCredit.Value,
                        IdKindOfSubject = dgvKindOfSubjectList.CurrentRow != null ?
                        Convert.ToInt32(dgvKindOfSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value) : 0,
                        Id = Convert.ToInt32(dgvSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value)
                    };
                    string message;

                    if (_business.EditSubjectValidator(subject, out message))
                    {
                        if (!_business.EditSubject(subject))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.PROGRAM_NAME);
                            return;
                        }
                        ReloadSubject(subject);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                }
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteSubjectClick(object sender, EventArgs e)
        {
            try
            {
                var subjects = new List<Subject>();
                string message;

                for (var i = 0; i < dgvSubjectList.RowCount; i++)
                {
                    if (!(bool)dgvSubjectList[(string)typeof(Subject).Properties().IsChecked, i].Value) continue;

                    subjects.Add(new Subject
                    {
                        Id = (int)dgvSubjectList[(string)typeof(Subject).Properties().Id, i].Value,
                        Name = dgvSubjectList[(string)typeof(Subject).Properties().Name, i].Value.ToString(),
                        NumberOfCredit = dgvSubjectList.CurrentRow != null ?
                        Convert.ToInt32(dgvSubjectList.CurrentRow.Cells["NumberOfCredit"].Value) : 0,
                        IdKindOfSubject = dgvSubjectList.CurrentRow != null ?
                        Convert.ToInt32(dgvSubjectList.CurrentRow.Cells["IdKindOfSubject"].Value) : 0
                    });
                }

                if (subjects.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                    return;
                }

                if (_business.DeleteSubjectValidator(subjects, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các môn học đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteSubjects(subjects);
                        ReloadSubject(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void PicSearchSubjectClick(object sender, EventArgs e)
        {
            var keyNameSubject = txtSearchSubject.Text.Trim();

            if (string.IsNullOrEmpty(keyNameSubject))
                dgvSubjectList.DataSource = _business.GetListSubject();

            dgvSubjectList.DataSource = _business.GetListSubjectByKeyNameSubject(keyNameSubject);

            txtSubject.Text = string.Empty;
        }

        #endregion

        #region -- Subject required --

        private void LoadSubjectRequired()
        {
            if (dgvSubjectList.CurrentRow == null) return;

            cboSubjectRequired.DataSource = _business.GetListSubject(Convert.ToInt32(dgvSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value));

            cboSubjectRequired.DisplayMember = PropertiesConstants.Name;
            cboSubjectRequired.ValueMember = PropertiesConstants.Id;

            dgvSubjectRequiredList.DataSource =
                _business.GetListSubjectRequireBySubject(
                    (int)dgvSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value);

            if (dgvSubjectRequiredList.DataSource == null)
                dgvSubjectRequiredList.Rows.Clear();

            lblSubject.Text = string.Format(ConstantMessages.LabelSubject,
                                            (dgvSubjectList.CurrentRow.Cells[PropertiesConstants.Name].Value));

            DataGridViewHelper.ChangeDgvStyleDataGridView(dgvSubjectRequiredList);

            DataGridViewHelper.ShowHideColumns(dgvSubjectRequiredList,
                                               new[] { PropertiesConstants.IsChecked, "SubjectRequireName" });

            SubjectRequiredCurrentRowChanged();

            DataGridViewHelper.ShowIsCheck(dgvSubjectRequiredList);

            DataGridViewHelper.ApplyUncheckedAll(dgvSubjectRequiredList);
        }

        private void ReloadSubjectRequire(SubjectRequire subjectrRequire)
        {
            LoadSubjectRequired();
            DataGridViewHelper.SetDgvCurrentCell(dgvSubjectList, subjectrRequire.SubjectName);
            SubjectRequiredCurrentRowChanged();
        }

        private void SubjectRequiredCurrentRowChanged()
        {
            if (dgvSubjectRequiredList.CurrentRow != null)
            {
                dgvSubjectRequiredList.CurrentRow.Cells[PropertiesConstants.IsChecked].Value = true;
            }
        }

        private void DgvSubjectRequiredListCurrentCellChanged(object sender, EventArgs e)
        {
            SubjectRequiredCurrentRowChanged();
        }

        private void CkbAllSubjectRequiredCheckedChanged(object sender, EventArgs e)
        {
            if (ckbAllSubjectRequired.Checked)
            {
                DataGridViewHelper.ApplyCheckedAll(dgvSubjectRequiredList);

                ckbAllSubjectRequired.Text = string.Format("Hủy chọn tất cả");
            }
            else
            {
                DataGridViewHelper.ApplyUncheckedAll(dgvSubjectRequiredList);

                ckbAllSubjectRequired.Text = string.Format("Lựa chọn tất cả");
            }
        }

        private void DgvSubjectRequiredListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSubjectRequiredList == null) return;

            if (e.ColumnIndex != dgvSubjectRequiredList.Columns[PropertiesConstants.IsChecked].Index) return;

            dgvSubjectRequiredList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvSubjectRequiredList[e.ColumnIndex, e.RowIndex].Value;

            switch ((bool)dgvSubjectRequiredList[e.ColumnIndex, e.RowIndex].Value)
            {
                case false:
                    {
                        ckbAllSubjectRequired.Checked = false;

                        ckbAllSubjectRequired.Text = string.Format("Lựa chọn tất cả");
                    }
                    break;
                default:
                    if (DataGridViewHelper.AllRowsIsCheck(dgvSubjectRequiredList))
                    {
                        ckbAllSubjectRequired.Checked = true;

                        ckbAllSubjectRequired.Text = string.Format("Hủy chọn tất cả");
                    }
                    break;
            }
        }

        private void BtnAddSubjectRequiredClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvSubjectList.CurrentRow==null)
                {
                    MessageBox.Show("Không có môn học nào được chọn");
                    return;
                }

                var subjectRequire = new SubjectRequire
                {
                    IdSubject = Convert.ToInt32(dgvSubjectList.CurrentRow.Cells[PropertiesConstants.Id].Value),
                    IdSubjectRequire = Convert.ToInt32(((Subject)cboSubjectRequired.SelectedItem).Id)
                };

                string message;

                if (_business.AddNewSubjectRequireValidator(subjectRequire, out message))
                {
                    _business.AddNewSubjectRequire(subjectRequire);
                    ReloadSubjectRequire(subjectRequire);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteSubjectRequiredClick(object sender, EventArgs e)
        {
            try
            {
                var subjectsRequire = new List<SubjectRequire>();
                string message;

                for (var i = 0; i < dgvSubjectRequiredList.RowCount; i++)
                {
                    if (!(bool)dgvSubjectRequiredList[(string)typeof(SubjectRequire).Properties().IsChecked, i].Value) continue;

                    subjectsRequire.Add(new SubjectRequire
                    {
                        Id = (int)dgvSubjectRequiredList[(string)typeof(SubjectRequire).Properties().Id, i].Value,
                        IdSubject = dgvSubjectRequiredList.CurrentRow != null ?
                        Convert.ToInt32(dgvSubjectRequiredList.CurrentRow.Cells["IdSubject"].Value) : 0,
                        IdSubjectRequire = dgvSubjectRequiredList.CurrentRow != null ?
                        Convert.ToInt32(dgvSubjectRequiredList.CurrentRow.Cells["IdSubjectRequire"].Value) : 0
                    });
                }

                if (subjectsRequire.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                    return;
                }

                if (_business.DeleteSubjectRequireValidator(subjectsRequire, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các điều kiện tiên quyết đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteSubjectRequires(subjectsRequire);
                        ReloadSubject(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion
    }
}